﻿using HalconDotNet;
using MvCamCtrl.NET;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VisionBasicSystem.Service
{
    public class MyDisposeImage
    {
        /// <summary>
        /// Bitmap位图转halcon Hobject图像类型
        /// </summary>
        /// <param name="Width"></param>
        /// <param name="Height"></param>
        /// <param name="MyBitmap"></param>
        /// <returns></returns>
        public HObject BitmapToHobject(int Width, int Height, Bitmap MyBitmap)
        {
            HObject Image;

            BitmapData BitmapData = MyBitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
            unsafe
            {
                //图像数据排列BGR
                byte* Inptr = (byte*)(BitmapData.Scan0.ToPointer());
                byte[] R_OutBuffer = new byte[Width * Height];
                byte[] G_OutBuffer = new byte[Width * Height];
                byte[] B_OutBuffer = new byte[Width * Height];
                fixed (byte* R_Outptr = R_OutBuffer, G_Outptr = G_OutBuffer, B_Outptr = B_OutBuffer)
                {
                    for (int i = 0; i < Height; i++)
                    {
                        for (int j = 0; j < Width; j++)
                        {
                            int Index = (i * Width + j) * 4;
                            B_OutBuffer[Index / 4] = (byte)Inptr[Index + 0];
                            G_OutBuffer[Index / 4] = (byte)Inptr[Index + 1];
                            R_OutBuffer[Index / 4] = (byte)Inptr[Index + 2];
                        }
                    }
                    MyBitmap.UnlockBits(BitmapData);

                    HOperatorSet.GenImage3(out Image, "byte", Width, Height, new IntPtr(R_Outptr), new IntPtr(G_Outptr), new IntPtr(B_Outptr));

                    return Image;
                }
            }
        }
    }
}